package com.mushuilingfeng.ddd.user.service.impl;

import com.mushuilingfeng.ddd.user.bo.MobileLoginBO;
import com.mushuilingfeng.ddd.user.bo.UserPasswordLoginBO;
import com.mushuilingfeng.ddd.user.cover.IDataCover;
import com.mushuilingfeng.ddd.user.domain.base.BusinessException;
import com.mushuilingfeng.ddd.user.domain.base.Ii8nCode;
import com.mushuilingfeng.ddd.user.domain.user.dto.MobileLoginDto;
import com.mushuilingfeng.ddd.user.domain.user.dto.PasswordLoginDto;
import com.mushuilingfeng.ddd.user.domain.user.entity.User;
import com.mushuilingfeng.ddd.user.domain.user.service.impl.UserServiceImpl;
import com.mushuilingfeng.ddd.user.service.ITokenService;
import com.mushuilingfeng.ddd.user.service.IUserLoginService;
import com.mushuilingfeng.ddd.user.vo.UserLoginResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 沐水淋风
 * @date 2024/9/29
 */
@Service
@Slf4j
public class UserLoginServiceImpl implements IUserLoginService {
    @Resource
    private UserServiceImpl userService;
    @Resource
    private ITokenService tokenService;
    private final ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
    
    @Override
    public String getPasswordLoginVerifyCode(String clientId) {
        Random rd = new Random(System.currentTimeMillis());
        String code = "" + rd.nextInt(1000, 9999);
        map.put(clientId, code);
        return code;
    }
    
    private UserLoginResult toUserLoginResult(User user, String clientId) {
        if (null == user) {
            throw new BusinessException(Ii8nCode.ACCOUNT_OR_PASSWORD_ERROR);
        }
        UserLoginResult.UserLoginResultBuilder builder = UserLoginResult.builder();
        builder.user(IDataCover.INSTANCE.toUserVO(user));
        builder.token(tokenService.authenticate(user, clientId));
        builder.loginTime(new Date());
        return builder.build();
    }
    
    @Override
    public UserLoginResult passwordLogin(UserPasswordLoginBO bo) {
        if (!bo.getVerifyCode().equals(map.get(bo.getClientId()))) {
            //throw new BusinessException(Ii8nCode.VERIFY_CODE_ERROR);
            log.info("验证码不正确，请携带正确的验证码！！！（本项目是测试使用，不正式对验证码作拦截，权提示）");
        }
        PasswordLoginDto dto = IDataCover.INSTANCE.toPasswordLoginDto(bo);
        return toUserLoginResult(userService.passwordLogin(dto), bo.getClientId());
    }
    
    @Override
    public void sendMobileLoginVerifyCode(String tel) {
        userService.sendLoginVerifyCode(tel);
    }
    
    @Override
    public UserLoginResult mobileLogin(MobileLoginBO bo) {
        MobileLoginDto dto = IDataCover.INSTANCE.toMobileLoginDto(bo);
        return toUserLoginResult(userService.mobileLogin(dto), bo.getClientId());
    }
    
}
